package Euler271;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import ReusableCode.MathFunctions;
import ReusableCode.PrimeFunctions;

public class ModularCubes {
	public static void main(String[] args) 
	{
		//Set the number as a long and BigInt.
		long number = 99999999999L;
		BigInteger num = new BigInteger(String.valueOf(number));
		
		//Create a lists for the prime factors.
		List<Integer> primeFactors = PrimeFunctions.factorize(number);
		ArrayList<BigInteger> nums = new ArrayList<BigInteger>();
		
		BigInteger iterate = BigInteger.ONE;
		for(int i = 0; i < primeFactors.size(); i++)
		{
			List<Integer> solution = solveForSmallInteger(primeFactors.get(i));
			System.out.println(solution);
			if((solution.size()==0) || ((solution.size()==1) && solution.contains(1)))
			{
				iterate = iterate.multiply(new BigInteger(String.valueOf(primeFactors.get(i))));
			}
		}
		if(!iterate.equals(BigInteger.ONE))
		{
			BigInteger base = iterate;
			iterate = iterate.add(BigInteger.ONE);
			
			while(iterate.compareTo(num) <= 0)
			{
				if(iterate.pow(3).mod(num).equals(BigInteger.ONE))
				{
					nums.add(iterate);
				}
				iterate = iterate.add(base);
			}
		}
		else
		{
			nums = solveBruteForce(number);
		}
		
		System.out.println(nums);
		System.out.println(MathFunctions.getSetSum(nums));
	}
	
	static List<Integer> solveForSmallInteger(int num)
	{
		List<Integer> nums = new ArrayList<Integer>();
		
		int count = (int) Math.pow(num, 1.0/3.0);
		while(count < num)
		{
			if(((long)Math.pow(count,3))%num==1)
			{
				nums.add(count);
			}
			count++;
		}
		
		return nums;
	}
	
	static ArrayList<BigInteger> solveBruteForce(long num)
	{
		ArrayList<BigInteger> nums = new ArrayList<BigInteger>();
		
		int count = (int) Math.pow(num, 1.0/3.0);
		while(count < num)
		{
			if(((long)Math.pow(count,3))%num==1)
			{
				nums.add(new BigInteger(String.valueOf(count)));
			}
			count++;
		}
		
		return nums;
	}
 	
}
